package com.connector.base.message.model;

import com.alibaba.fastjson.JSONObject;
import com.connector.base.connection.Connection;
import com.connector.base.protocol.Packet;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;

public abstract class JsonBodyMessage extends BaseMessage
{
    public JsonBodyMessage(final Packet packet, final Connection connection) {
        super(packet, connection);
    }

    public JsonBodyMessage() {
    }

    @Override
    public byte[] encode() {
        final JSONObject resultObj = this.fieldToJson();
        return (resultObj == null) ? new byte[0] : resultObj.toJSONString().getBytes(Charsets.UTF_8);
    }

    @Override
    public void decode(final byte[] body) {
        final String json = new String(body, Charsets.UTF_8);
        if (!Strings.isNullOrEmpty(json)) {
            final JSONObject jsonBody = JSONObject.parseObject(json);
            this.jsonToFields(jsonBody);
        }
    }

    public abstract void jsonToFields(final JSONObject jsonBody);

    public abstract JSONObject fieldToJson();
}
